﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace olierFrm.Web
{
    public class Paging
    {
        System.Web.HttpRequest Request;
        public const int PageRow = 10;
        public int CurPage = 0;
        public int Pages = 0;
        public string Url { get; private set; }
        /// <summary>
        /// 样式设置，默认是 PageList
        /// </summary>
        public string Class { get; set; }
        public Paging(string Param, int RowCount, int PageRow = PageRow)
        {
            Request = System.Web.HttpContext.Current.Request;

            string url = Request.Url.ToString();
            if (Request.QueryString[Param] != null)
            {
                url = url.Replace(Param + "=" + Request.QueryString[Param], Param + "={0}");
                CurPage = int.Parse(Request.QueryString[Param]);
            }
            else
            {

                if (Request.QueryString.Keys.Count == 0)
                {
                    url += "?" + Param + "={0}";
                }
                else
                {
                    url += "&" + Param + "={0}";
                }
            }
            Pages = (RowCount + PageRow - 1) / PageRow;
            Url = url;
            Class = "PageList";
        }

        /// <summary>
        /// 输出HTML
        /// </summary>
        /// <returns></returns>
        public override string ToString()
        {
            string strHtml = "<div class='" + Class + "'>{0}</div>";
            string pageTemplate = "<a href='{0}'>{1}</a>";
            StringBuilder sbPages = new StringBuilder();
            int i = 0;
            while (i < Pages)
            {
                if (i == CurPage)
                {
                    sbPages.Append("<span>" + ++i + "</span>");
                    continue;
                }
                sbPages.Append(string.Format(pageTemplate, string.Format(Url, i++), i));
            }
            sbPages.Append("<span>共 " + Pages + " 页</span>");

            return string.Format(strHtml, sbPages.ToString());
        }
    }
}
